package com.springcloud.market.order.service.impl;


import com.springcloud.market.common.dto.OrderDTO;
import com.springcloud.market.common.entity.Order;
import com.springcloud.market.common.feign.StockFeignClient;
import com.springcloud.market.common.model.R;
import com.springcloud.market.order.mapper.OrderMapper;
import com.springcloud.market.order.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends OrderService {

    private final OrderMapper orderMapper;
    private final StockFeignClient stockFeignClient;

    @GlobalTransactional(rollbackFor = Exception.class) // 分布式事务
    @Override
    public String createOrder(OrderDTO dto) {
        // 扣库存
        R<Void> r = stockFeignClient.reduceStock(dto.getSkuId(), dto.getNum());
        if (r.getCode() != 200) {
            throw new RuntimeException("扣库存失败：" + r.getMsg());
        }

        // 创建订单
        Order order = new Order();
        order.setUserId(dto.getUserId());
        order.setSkuId(dto.getSkuId());
        order.setNum(dto.getNum());
        orderMapper.insert(order);

        return "订单创建成功，订单号：" + order.getId();
    }
}



//import com.springcloud.market.common.entity.Order;
//import com.springcloud.market.order.mapper.OrderMapper;
//import com.springcloud.market.order.service.OrderService;
//import com.springcloud.market.common.feign.StockFeignService;
//import io.seata.spring.annotation.GlobalTransactional;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//@Service
//public class OrderServiceImpl implements OrderService {
//
//    @Autowired
//    private OrderMapper orderMapper;
//
//    @Autowired
//    private StockFeignService stockFeignService;
//
//    @GlobalTransactional(rollbackFor = Exception.class)
//    @Transactional
//    @Override
//    public Order create(Order order) {
//        orderMapper.insert(order);
//        String msg = stockFeignService.reduce2(order.getProductId());
//        System.out.println(msg);
//        int i = 1 / 0; // 故意异常
//        return order;
//    }
//}